//
//  MyQrCodeVC.swift
//  kxf
//
//  Created by Mac on 2024/3/9.
//

import Foundation
import UIKit
import Photos
import MCToast

class MyQrCodeVC: WHBaseViewVC {
    
    let qrCodeUrl = "\(URL_sn_qrcode)\(UserModel.shared.memberId)&sn=\(UserModel.shared.sn)"
    var urlString = ""
    
    var imageUrl = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        if imageUrl.count > 0 {
            self.urlString = imageUrl
            self.qrCodeImgView.setImgUrl(urlString: "\(imageUrl)")
        }else{
            if UserModel.shared.codePlateUrl.count > 5 {
                self.urlString = UserModel.shared.codePlateUrl
                self.qrCodeImgView.setImgUrl(urlString: "\(UserModel.shared.codePlateUrl)")
            }else{
                sendQrcodeRequest()
            }
        }
    }
    lazy var bgView : UIView = {
        let vi = UIView()
        vi.backgroundColor = WHColorWithAlpha(colorStr: "F10E0E", alpha: 0.1)
        vi.isUserInteractionEnabled = true
        
        return vi
    }()
    lazy var bgImgView : UIImageView = {
        let img = UIImageView()
        img.setImgLocal(imgName: "mine_qrcode_bg")
        
        return img
    }()
    lazy var titelLab : UILabel = {
        let lab = UILabel()
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 18, weight: .medium)
        lab.layer.cornerRadius = kFitWidth(24)
        lab.clipsToBounds = true
        lab.textAlignment = .center
        lab.backgroundColor = WHColor_16(colorStr: "F4F4F4")
        lab.text = "我的码牌"
        
        return lab
    }()
    lazy var qrCodeImgView : UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFit
        
        return img
    }()
    lazy var saveBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("下载保存", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        btn.setBackgroundImage(UIImage.init(named: "qrcode_btn_bg"), for: .normal)
        btn.backgroundColor = .clear
        btn.titleEdgeInsets = UIEdgeInsets(top: -kFitWidth(5), left: 0, bottom: 0, right: 0)
        
        btn.addTarget(self, action: #selector(saveAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var shareBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("分享转发", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        btn.setBackgroundImage(UIImage.init(named: "qrcode_btn_bg"), for: .normal)
        btn.backgroundColor = .clear
        btn.titleEdgeInsets = UIEdgeInsets(top: -kFitWidth(5), left: 0, bottom: 0, right: 0)
        
        btn.addTarget(self, action: #selector(shareAction), for: .touchUpInside)
        return btn
    }()
}

extension MyQrCodeVC{
    @objc func shareAction()  {
        let message =  WXMediaMessage()
        
        let imageObject =  WXImageObject()
        let img = qrCodeImgView.mc_makeImage()
        imageObject.imageData = img.pngData()!
        message.mediaObject = imageObject
        let req =  SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(WXSceneSession.rawValue)
        WXApi.send(req)

    }
}

extension MyQrCodeVC{
    func initUI() {
        initNavi(titleStr: "我的码牌")
        
//        view.backgroundColor = WHColorWithAlpha(colorStr: "F10E0E", alpha: 0.2)
        view.addSubview(bgView)
//        view.addSubview(bgImgView)
//        bgImgView.addSubview(titelLab)
//        bgImgView.addSubview(qrCodeImgView)
        
        view.addSubview(scrollView)
        scrollView.addSubview(qrCodeImgView)
        scrollView.addSubview(saveBtn)
        scrollView.addSubview(shareBtn)
        
        scrollView.frame = CGRect.init(x: 0, y: getNavigationBarHeight(), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-getNavigationBarHeight())
        scrollView.backgroundColor = .clear
        scrollView.contentSize = CGSize.init(width: 0, height: kFitWidth(650))
        
        setConstrait()
        
        
    }
    func setConstrait() {
        bgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(getNavigationBarHeight())
        }
//        bgImgView.snp.makeConstraints { make in
//            make.centerX.lessThanOrEqualToSuperview()
//            make.width.equalTo(kFitWidth(343))
//            make.height.equalTo(kFitWidth(426))
//            make.top.equalTo(getNavigationBarHeight()+kFitWidth(20))
//        }
//        titelLab.snp.makeConstraints { make in
//            make.centerX.lessThanOrEqualToSuperview()
//            make.top.equalTo(kFitWidth(45))
//            make.width.equalTo(kFitWidth(216))
//            make.height.equalTo(kFitWidth(48))
//        }
//        qrCodeImgView.snp.makeConstraints { make in
//            make.centerX.lessThanOrEqualToSuperview()
//            make.top.equalTo(kFitWidth(138))
//            make.width.equalTo(kFitWidth(177.27))
//            make.height.equalTo(kFitWidth(240))
//        }
        qrCodeImgView.snp.makeConstraints { make in
            make.left.width.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(kFitWidth(507))
        }
        saveBtn.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(35))
            make.top.equalTo(qrCodeImgView.snp.bottom).offset(kFitWidth(30))
            make.width.equalTo(kFitWidth(108))
            make.height.equalTo(kFitWidth(44))
        }
        shareBtn.snp.makeConstraints { make in
//            make.right.equalTo(kFitWidth(-35))
            make.left.equalTo(kFitWidth(232))
            make.width.height.equalTo(saveBtn)
            make.centerY.lessThanOrEqualTo(saveBtn)
        }
    }
}

extension MyQrCodeVC{
    @objc func saveAction() {
        PHPhotoLibrary.requestAuthorization { (status) in
            DispatchQueue.main.async {
                if status == .restricted || status == .denied{
                    self.presentAlertVc(confirmBtn: "打开", message: "无访问相册权限，是否去打开权限?", title: "提示", cancelBtn: "取消", handler: { (actions) in
                        let url = NSURL.init(string: UIApplication.openSettingsURLString)
                        if UIApplication.shared.canOpenURL(url! as URL){
                            UIApplication.shared.openURL(url! as URL)
                        }
                    }, viewController: self)
                }else{
                    MCToast.mc_loading(text: "码牌保存中", autoClearTime: 30)
                    let image = self.qrCodeImgView.mc_makeImage()
                    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            }
        }
    }
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject){
        MCToast.mc_remove()
        if error != nil{
            self.presentAlertVcNoAction(title: "保存失败", viewController: self)
        }else{
            MCToast.mc_text("码牌已保存到相册！")
        }
    }
}

extension MyQrCodeVC{
    func sendQrcodeRequest() {
        MCToast.mc_loading()
        
        let param = ["waterMarkContent":"\(UserModel.shared.mchName)",
                     "qrCodeUrl":"\(qrCodeUrl)",
                     "type":"102",
                     "backgroundUrl":"https://yukuaifu.oss-cn-beijing.aliyuncs.com/1afe4e8e7d77feac929e7c7a80acfd3.png"]
        
        WHNetworkUtil.shareManager().POST(urlString: URL_sn_get_qrcode, parameters: param as? [String : AnyObject],isNeedToast: true,vc:self) { responseObject in
            DLLog(message: "\(responseObject)")
            self.urlString = "\(responseObject["data"]as? String ?? "")"
            self.qrCodeImgView.setImgUrl(urlString: "\(self.urlString)")
        }
    }
}
